package com.bp.hearthealth.pulse.lnapps.bp_view

import android.content.Context
import android.os.AsyncTask
import android.os.CountDownTimer
import android.os.Handler
import android.os.Looper
import android.os.Parcel
import android.os.Parcelable
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.bp.hearthealth.pulse.lnapps.bp_itfc.TimerFinishedBpListener

class BPCountDownTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
) : AppCompatTextView(context, attrs, defStyleAttr) {

    private var countDownTimer: CountDownTimer? = null
    private var initialMillis: Long = 0
    private var currentMillis: Long = 0
    private var isCountingDown: Boolean = false

    companion object {
        private const val KEY_INITIAL_MILLIS = "initial_millis"
        private const val KEY_CURRENT_MILLIS = "current_millis"
        private const val KEY_IS_COUNTING_DOWN = "is_counting_down"
        private const val KEY_SUPER_STATE = "super_state"
    }

    init {
        isClickable = true
        setOnClickListener {
            toggleCountDown()
        }
    }

    override fun onSaveInstanceState(): Parcelable? {
        val superState = super.onSaveInstanceState()
        return CountDownSavedState(superState, initialMillis, currentMillis, isCountingDown)
    }

    override fun onRestoreInstanceState(state: Parcelable?) {
        if (state is CountDownSavedState) {
            super.onRestoreInstanceState(state.superState)
            initialMillis = state.initialMillis
            currentMillis = state.currentMillis
            isCountingDown = state.isCountingDown
            updateText()
            if (isCountingDown) {
                startCountDown(currentMillis)
            }
        } else {
            super.onRestoreInstanceState(state)
        }
    }

    private fun startCountDown(durationMillis: Long) {
        initialMillis = durationMillis
        currentMillis = initialMillis

        countDownTimer?.cancel() // 取消之前的倒计时

        countDownTimer = object : CountDownTimer(currentMillis, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                currentMillis = millisUntilFinished
                updateText()
            }

            override fun onFinish() {
                currentMillis = 0
                // 在倒计时结束后，显示为 "00:00"
                text = "00:00"
//                startCountDown(Configuration.HOME_TIMER)
                timerFinished?.timerFinished()
            }
        }

        countDownTimer?.start()
        isCountingDown = true
    }

    private var timerFinished: TimerFinishedBpListener?=null
    fun setTimerFinishedListener(timerFinishedListener: TimerFinishedBpListener){
        this.timerFinished = timerFinishedListener
    }

    private fun updateText() {
        AsyncTask.execute {
            // 耗时操作
            val minutes = currentMillis / 60000
            val seconds = (currentMillis % 60000) / 1000
            // 通过 Handler 切换回主线程更新 UI
            Handler(Looper.getMainLooper()).post {
                text = if (currentMillis <= 0) {
                    "00:00"
                } else {
                    String.format("%02d:%02d", minutes, seconds)
                }
            }
        }

    }



    fun pauseCountDown() {
        countDownTimer?.cancel()
        isCountingDown = false
    }

    fun toggleCountDown() {
        if (isCountingDown) {
            pauseCountDown()
        } else {
            startCountDown(currentMillis)
        }
    }

    fun getCurrentMillis(): Long {
        return currentMillis
    }

    private class CountDownSavedState : BaseSavedState {
        var initialMillis: Long = 0
        var currentMillis: Long = 0
        var isCountingDown: Boolean = false

        constructor(
            superState: Parcelable?,
            initialMillis: Long,
            currentMillis: Long,
            isCountingDown: Boolean,
        ) : super(superState) {
            this.initialMillis = initialMillis
            this.currentMillis = currentMillis
            this.isCountingDown = isCountingDown
        }

        constructor(parcel: Parcel) : super(parcel) {
            initialMillis = parcel.readLong()
            currentMillis = parcel.readLong()
            isCountingDown = parcel.readByte() != 0.toByte()
        }

        override fun writeToParcel(out: Parcel, flags: Int) {
            super.writeToParcel(out, flags)
            out.writeLong(initialMillis)
            out.writeLong(currentMillis)
            out.writeByte(if (isCountingDown) 1 else 0)
        }

        companion object CREATOR : Parcelable.Creator<CountDownSavedState> {
            override fun createFromParcel(parcel: Parcel): CountDownSavedState {
                return CountDownSavedState(parcel)
            }

            override fun newArray(size: Int): Array<CountDownSavedState?> {
                return arrayOfNulls(size)
            }
        }
    }
}
